package com.gantrylau.examples.rxjava;

import org.junit.Test;
import rx.Observable;
import rx.Subscriber;


/**
 * @author gantrylau
 * @since 2016年08月22日
 */
public class RxJavaExample {

    /**
     * 这是最简单的一个创建的例子
     */
    @Test
    public void createSimpleObservable() {
        Observable<String> myObservable = Observable.create(
                new Observable.OnSubscribe<String>() {
                    @Override
                    public void call(Subscriber<? super String> sub) {
                        try {
                            sub.onNext("您好!");
                            sub.onCompleted();
                        } catch (Exception e) {
                            sub.onError(e);
                        }
                    }
                }
        );

        Subscriber<String> mySubscriber = new Subscriber<String>() {
            @Override
            public void onNext(String s) {
                System.out.println(s);
            }

            @Override
            public void onCompleted() {
                System.out.println("处理消息完成");
            }

            @Override
            public void onError(Throwable e) {
                System.out.println("出错了");
            }
        };

        myObservable.subscribe(mySubscriber);
    }

    /**
     * 这是Observable另外一种简洁的写法
     */
    @Test
    public void createSimpleObservable2() {
        Observable.just("您好!").subscribe(new Subscriber<String>() {
            @Override
            public void onCompleted() {
                System.out.println("处理消息完成");
            }

            @Override
            public void onError(Throwable throwable) {
                System.out.println("出错了"+throwable.getMessage());
            }

            @Override
            public void onNext(String s) {
                System.out.println(s);
                throw new RuntimeException("这个错误用来测试");
            }
        });
    }
}
